// pages/saleOrder/component/detailView.js
import {formatDate} from "../../../utils/util";
import network from "../../../utils/network";
import Toast from "@vant/weapp/toast/toast";
import {add, divide, multiply} from "../../../utils/amount";
import Dialog from '@vant/weapp/dialog/dialog';
import Validate from "../../../utils/validate";

const util = require('../../../utils/util')

const app = getApp()

Component({
    /**
     * 组件的属性列表
     */
    properties: {
        saleId: {
            type: Number,
            value: -1
        },
        create: {
            type: Boolean,
            value: false
        },
        is_update: {
            type: Boolean,
            value: false
        },
        params: {
            type: Object,
            value: {}
        }
    },
    ready() {
        util.showLoading('加载中')
        Promise.all([this.initCompanyArr(), this.initCustomerArr()]
        ).then(() => {
                util.hideLoading()
            }
        ).catch(() => {
            util.hideLoading()
        })
        this.initValidate()
        this.initValidateProxyMediaDetail()
        this.initValidateMediaDetail()
        this.selectComponent('.flow-btn-group').callbackBeforeConfirm = () => {
            return this.validateData();
        }
    },
    /**
     * 组件的初始数据
     */
    data: {
        activeNames: [],
        activeNames2: [],
        activeNames3: [],
        cuForm: {
            // 客户id
            customer_id: null,
            // 合同id
            choose_id: null,
            // 点位选择id
            contract_choose_id: null,
            // 日期范围id
            contract_daterange_id: null,
            // 填表日期
            fill_date: formatDate(new Date()),
            // 合同ID
            contract_id: null,
            // 分公司id
            dept_id: null,
            actual_execute_time: [],
            // 实际执行开始时间
            actual_execute_time_start: null,
            // 实际执行结束时间
            actual_execute_time_end: null,
            // 本次发布金额
            release_amount: null,
            // 本次换画面金额
            replace_amount: null,
            // 本次执行金额
            execute_amount: null,
            // 代理公司名称
            proxy_company_name: null,
            // 代理金额
            proxy_amount: null,
            // 被代理公司名称
            proxied_company_name: null,
            // 被代理金额
            proxied_amount: null,
            // 是否置换：1：是，0：否
            need_replace: null,
            // 物品金额
            item_amount: null,
            // 现金金额
            cash_amount: null,
            // 计提额
            accrued_amount: null,
            // 收款时间
            collection_time: null,
            // 是否开发票：1：是，0：否
            need_invoice: null,
            // 备注
            memo: null,
            discount: null,
            // 媒体类型对应数量金额
            billSaleMediaAmountList: [],
            // 代理信息
            billSaleProxyList: [{
                proxy_company_name: null,
                proxy_amount: null,
                proxyMediaDetailList: [{
                    proxy_media_type: null,
                    media_type_spec: null,
                    quantity: null,
                    duration: null,
                    amount: null,
                    fill_amount: null
                }],
                activeNames4: ['1']
            }],
            tmpDataList: [],
            proxyInfo: [],
            proxyInfo2: [],
            contractAmount: null,
            dateRangeBeginDate: null,
            dateRangeEndDate: null,
            contractBeginDate: '',
            contractEndDate: '',
            contractName: '',
            contract: null,
            intention_scheme_id: null,
            intention_scheme: null,
            daterange_id: null,
            contract_num: null,
            update_accrued_amount: false,
            billSaleMediaCycle: null,
            customerName: null,
            planName: null,
            deptName: null,
            type: 1,
            can_check: false
        },
        billSaleMediaCycle: {
            day: null,
            cycle_arr: []
        },
        media_type_count_amount_arr: [],
        not_fill: false,// 是否可填写计提百分比
        dateShow: false,
        customer_arr: [],
        selectCustomerLoading: true,
        company_arr: [],
        selectCompanyLoading: true,
        contractList: [],
        selectContractLoading: true,
        selectPlanLoading: true,
        planList: [],
        tmpContract: null,
        related_type: 1,
        must_include_id: '',
        validate: {},
        validateMediaDetail: {},
        validateProxyMediaDetail: {},
        user_id: wx.getStorageSync('user_id'),
        showSettingSaleCycle: false,
        allDay: 0,
        beforeClose: (e) => {
            return e === 'cancel'
        },
    },

    /**
     * 组件的方法列表
     */
    methods: {
        // 验证函数
        initValidate() {
            const rules = {
                customer_id: {
                    required: true
                },
                type: {
                    required: true
                },
                contract_id: {
                    required: true,
                },
                dept_id: {
                    required: true
                },
                intention_scheme_id: {
                    required: true
                },
                daterange_id: {
                    required: true
                },
                execute_amount: {
                    required: true
                },
                need_replace: {
                    required: true
                },
                need_invoice: {
                    required: true
                },
                collection_time: {
                    required: true
                }
            }
            const messages = {
                customer_id: {
                    required: '请选择项目'
                },
                type: {
                    required: '请选择销售单类型'
                },
                contract_id: {
                    required: '请选择合同',
                },
                dept_id: {
                    required: '请选择公司名称'
                },
                intention_scheme_id: {
                    required: '请选择方案'
                },
                daterange_id: {
                    required: '请选择方案'
                },
                execute_amount: {
                    required: '执行金额不能为空'
                },
                need_replace: {
                    required: '请选择是否置换'
                },
                need_invoice: {
                    required: '请选择是否开票'
                },
                collection_time: {
                    required: '请选择收款时间'
                }
            }
            this.data.validate = new Validate(rules, messages)
        },
        // 验证函数
        initValidateMediaDetail() {
            const rules = {
                fill_amount: {
                    required: true
                }
            }
            const messages = {
                fill_amount: {
                    required: '请输入总价'
                }
            }
            this.data.validateMediaDetail = new Validate(rules, messages)
        },
        initValidateProxyMediaDetail() {
            const rules = {
                proxy_media_type: {
                    required: true
                },
                media_type_spec: {
                    required: true
                },
                quantity: {
                    required: true
                },
                duration: {
                    required: true
                },
                amount: {
                    required: true
                },
                fill_amount: {
                    required: true
                }
            }
            const messages = {
                proxy_media_type: {
                    required: '代理媒体类型不能为空'
                },
                media_type_spec: {
                    required: '规格不能为空'
                },
                quantity: {
                    required: '数量不能为空'
                },
                duration: {
                    required: '时长不能为空'
                },
                amount: {
                    required: '金额不能为空'
                },
                fill_amount: {
                    required: '刊例总价不能为空'
                }
            }
            this.data.validateProxyMediaDetail = new Validate(rules, messages)
        },
        onChange(e) {
            this.setData({
                activeNames: e.detail
            })
        },
        onChange2(e) {
            this.setData({
                activeNames2: e.detail
            })
        },
        onChange3(e) {
            this.setData({
                activeNames3: e.detail
            })
        },
        onChange4(e) {
            let key = 'cuForm.billSaleProxyList[' + e.target.dataset.index + '].activeNames4'
            this.setData({
                [key]: e.detail
            })
        },
        onDateConfirm(e) {
            this.setData({
                'cuForm.collection_time': formatDate(e.detail),
                dateShow: false,
            })
        },
        onDateClose() {
            this.setData({
                dateShow: false,
            })
        },
        showCalendar() {
            if (this.data.cuForm.flow_status !== 3 && this.data.cuForm.flow_status !== 4) {
                this.setData({
                    dateShow: true,
                })
            }
        },

        selectCustomerConfirm(e) {
            this.setData({
                'cuForm.customer_id': e.detail.value.id,
                'cuForm.customerName': e.detail.value.name,
                'cuForm.contractAmount': null,
                'cuForm.contract_id': null,
                'cuForm.contractName': null,
                'cuForm.contract_num': null,
                'cuForm.planName': null,
                'cuForm.actual_execute_time_start': null,
                'cuForm.actual_execute_time_end': null,
                'cuForm.choose_id': null,
                'cuForm.intention_scheme_id': null,
                'cuForm.daterange_id': null,
                not_fill: e.detail.value.is_company_customer
            })
            this.getContractArr(e.detail.value.id)
        },
        selectCompanyConfirm(e) {
            this.setData({
                'cuForm.dept_id': e.detail.value.id,
                'cuForm.deptName': e.detail.value.head,
            })
        },
        async selectContractConfirm(e) {
            this.setData({
                'cuForm.contractAmount': e.detail.value.discounted_price,
                'cuForm.contract_id': e.detail.value.id,
                'cuForm.contractName': e.detail.value.name,
                'cuForm.contract_num': e.detail.value.contract_num,
                'cuForm.dept_id': e.detail.value.dept_id,
                'cuForm.deptName': e.detail.value.bank_account_name,
                'cuForm.planName': null,
                'cuForm.actual_execute_time_start': null,
                'cuForm.actual_execute_time_end': null,
                'cuForm.choose_id': null,
                'cuForm.intention_scheme_id': null,
                'cuForm.daterange_id': null
            })
            util.showLoading('加载中')
            Promise.all([this.getContractDetail(e.detail.value.id), this.getPlanArr(e.detail.value.id, this.data.related_type, this.data.must_include_id, this.data.cuForm.type)]).then(res => {
                util.hideLoading()
            }).catch(() => {
                util.hideLoading()
            })
        },
        async selectPlanConfirm(e) {
            this.setData({
                'cuForm.planName': e.detail.value.plan_name,
                'cuForm.actual_execute_time_start': e.detail.value.daterange_start_at,
                'cuForm.actual_execute_time_end': e.detail.value.daterange_end_at,
                'cuForm.choose_id': e.detail.value.choose_id,
                'cuForm.intention_scheme_id': e.detail.value.id,
                'cuForm.daterange_id': e.detail.value.daterange_id
            })
            util.showLoading('加载中')
            const that = this
            await network.reqPromise("GET", {
                uri: app.api.media_type_count_amount,
                params: {customerId: that.data.cuForm.customer_id, dateRangeId: that.data.cuForm.daterange_id}
            }).then(res => {
                for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].media_type_id !== 1) {
                        res.data[i].amount = null
                    }
                }
                that.setData({
                    media_type_count_amount_arr: res.data.filter(item => item.spec_count != 0)
                })
                that.setData({
                    'cuForm.billSaleMediaAmountList': res.data.filter(item => item.spec_count != 0).map(item => {
                        return {
                            media_type_spec_id: item.media_type_spec_id,
                            media_type_spec_price_id: item.media_type_spec_price_id,
                            name: item.name,
                            media_count: item.spec_count,
                            fill_amount: null,
                            has_price_day: item.has_price_day,
                            has_price_week: item.has_price_week,
                            has_price_month: item.has_price_month,
                            price: null
                        }
                    })
                })
                util.hideLoading()
            }).catch(() => {
                Toast.fail({
                    message: '获取刊例总价失败',
                    context: that,
                    selector: '#custom-selector'
                });
                util.hideLoading()
            })
        },
        removeProxyDetail(e) {
            const index = e.target.dataset.i
            this.data.cuForm.billSaleProxyList[e.target.dataset.index].proxyMediaDetailList.splice(index, 1)
            this.setData({
                'cuForm.billSaleProxyList': this.data.cuForm.billSaleProxyList
            })
        },
        addProxy() {
            if (this.data.tmpContract) {
                this.data.cuForm.billSaleProxyList.push({
                    proxy_company_name: null,
                    proxy_amount: null,
                    proxyMediaDetailList: JSON.parse(JSON.stringify(this.data.tmpContract.proxyMediaDetailList)),
                    activeNames4: ['1']
                })
            } else {
                this.data.cuForm.billSaleProxyList.push({
                    proxy_company_name: null,
                    proxy_amount: null,
                    proxyMediaDetailList: [{
                        proxy_media_type: null,
                        media_type_spec: null,
                        quantity: null,
                        duration: null,
                        amount: null,
                        fill_amount: null
                    }],
                    activeNames4: ['1']
                })
            }
            this.setData({
                'cuForm.billSaleProxyList': this.data.cuForm.billSaleProxyList
            })
        },
        removeProxy(e) {
            const index = e.target.dataset.index
            this.data.cuForm.billSaleProxyList.splice(index, 1)
            this.setData({
                'cuForm.billSaleProxyList': this.data.cuForm.billSaleProxyList
            })
        },
        inputChange(e) {
            this.setData({
                [e.target.dataset.key]: e.detail
            })
        },
        fillAmountChange(e) {
            this.setData({
                [e.target.dataset.key]: e.detail
            })
            let item = this.data.cuForm.billSaleMediaAmountList[e.target.dataset.index]
            if (e.detail) {
                // 计算出每天的价格
                let num = divide(e.detail, multiply(item.media_count, this.data.allDay))
                if (num.toString().indexOf('.') > -1) {
                    num = parseFloat(num.toString().substr(0, num.toString().indexOf('.') + 5))
                }
                item.day_price = num.toFixed(2)
                item.week_price = multiply(num, 7).toFixed(2)
                item.month_price = multiply(num, 30).toFixed(2)
            }
            let key = 'cuForm.billSaleMediaAmountList[' + e.target.dataset.index + ']'
            this.setData({
                [key]: item
            })
            console.log(this.data.cuForm.billSaleMediaAmountList)
        },
        typeRadioChange(e) {
            const that = this
            if (this.data.cuForm.type == e.detail) {
                return
            }
            Dialog.confirm({
                title: '切换类型',
                message: '切换类型到丢失已经填写的数据 您确定切换？',
                context: that
            }).then(() => {
                this.setData({
                    cuForm: {
                        // 客户id
                        customer_id: null,
                        // 合同id
                        choose_id: null,
                        // 点位选择id
                        contract_choose_id: null,
                        // 日期范围id
                        contract_daterange_id: null,
                        // 填表日期
                        fill_date: formatDate(new Date()),
                        // 合同ID
                        contract_id: null,
                        // 分公司id
                        dept_id: null,
                        actual_execute_time: [],
                        // 实际执行开始时间
                        actual_execute_time_start: null,
                        // 实际执行结束时间
                        actual_execute_time_end: null,
                        // 本次发布金额
                        release_amount: null,
                        // 本次换画面金额
                        replace_amount: null,
                        // 本次执行金额
                        execute_amount: null,
                        // 代理公司名称
                        proxy_company_name: null,
                        // 代理金额
                        proxy_amount: null,
                        // 被代理公司名称
                        proxied_company_name: null,
                        // 被代理金额
                        proxied_amount: null,
                        // 是否置换：1：是，0：否
                        need_replace: null,
                        // 物品金额
                        item_amount: null,
                        // 现金金额
                        cash_amount: null,
                        // 计提额
                        accrued_amount: null,
                        // 收款时间
                        collection_time: null,
                        // 是否开发票：1：是，0：否
                        need_invoice: null,
                        // 备注
                        memo: null,
                        discount: null,
                        // 媒体类型对应数量金额
                        billSaleMediaAmountList: [],
                        // 代理信息
                        billSaleProxyList: [{
                            proxy_company_name: null,
                            proxy_amount: null,
                            proxyMediaDetailList: [{
                                proxy_media_type: null,
                                media_type_spec: null,
                                quantity: null,
                                duration: null,
                                amount: null,
                                fill_amount: null
                            }],
                            activeNames4: ['1']
                        }],
                        tmpDataList: [],
                        proxyInfo: [],
                        proxyInfo2: [],
                        contractAmount: null,
                        dateRangeBeginDate: null,
                        dateRangeEndDate: null,
                        contractBeginDate: '',
                        contractEndDate: '',
                        contractName: '',
                        contract: null,
                        intention_scheme_id: null,
                        intention_scheme: null,
                        daterange_id: null,
                        contract_num: null,
                        update_accrued_amount: false,
                        billSaleMediaCycle: null,
                        customerName: null,
                        planName: null,
                        deptName: null,
                        type: e.detail,
                    }
                })
            }).catch(() => {
                this.setData({
                    'cuForm.type': e.detail === 1 ? 2 : 1
                })
            });

        },
        radioChange(e) {
            this.setData({
                [e.target.dataset.key]: e.detail
            })
        },
        initCustomerArr() {
            const that = this
            return new Promise((resolve, reject) => {
                network.reqPromise("GET", {
                    uri: app.api.customerList
                }).then(res => {
                    that.setData({
                        customer_arr: res.data,
                        selectCustomerLoading: false
                    })
                    resolve()
                }).catch(() => {
                    Toast.fail({
                        message: '初始化客户失败',
                        context: that,
                        selector: '#custom-selector'
                    });
                    reject()
                })
            })
        },
        getContractArr(id) {
            util.showLoading('加载中')
            const that = this
            network.reqPromise("GET", {
                uri: app.api.contractListByCustomerId,
                params: {customerId: id}
            }).then(res => {
                res.data.forEach(item => {
                    item.name = item.part_a + '——' + item.contract_num + '（' + item.contract_begin_date + ' ~ ' + item.contract_end_date + '）'
                })
                that.setData({
                    contractList: res.data,
                    selectContractLoading: false
                })
                util.hideLoading()
            }).catch(() => {
                Toast.fail({
                    message: '初始化合同失败',
                    context: that,
                    selector: '#custom-selector'
                });
                util.hideLoading()
            })
        },
        initCompanyArr() {
            const that = this
            return new Promise((resolve, reject) => {
                network.reqPromise("GET", {
                    uri: app.api.companyList
                }).then(res => {
                    that.setData({
                        company_arr: res.data,
                        selectCompanyLoading: false
                    })
                    resolve()
                }).catch(() => {
                    Toast.fail({
                        message: '初始化公司失败',
                        context: that,
                        selector: '#custom-selector'
                    });
                    reject()
                })
            })
        },
        getPlanArr(related_id, related_type, must_include_id, type) {
            const that = this
            return new Promise((resolve, reject) => {
                network.reqPromise("GET", {
                    uri: app.api.planListById,
                    params: {
                        related_id: related_id,
                        related_type: related_type,
                        type: type,
                        must_include_id: must_include_id
                    }
                }).then(res => {
                    that.setData({
                        planList: res.data,
                        selectPlanLoading: false
                    })
                    resolve(res.data)
                }).catch(() => {
                    Toast.fail({
                        message: '初始化锁位方案失败',
                        context: that,
                        selector: '#custom-selector'
                    });
                    reject()
                })
            })
        },
        getContractDetail(id) {
            const that = this
            return new Promise((resolve, reject) => {
                network.reqPromise("GET", {
                    uri: app.api.contractDetail + '/' + id
                }).then(res => {
                    that.setData({
                        tmpContract: res.data
                    })
                    if (that.data.cuForm.billSaleProxyList && that.data.cuForm.billSaleProxyList.length) {
                        that.setData({
                            'cuForm.billSaleProxyList[0].proxyMediaDetailList': JSON.parse(JSON.stringify(res.data.proxyMediaDetailList))
                        })
                    } else {
                        that.setData({
                            'cuForm.billSaleProxyList[0]': {
                                proxy_company_name: null,
                                proxy_amount: null,
                                proxyMediaDetailList: JSON.parse(JSON.stringify(res.data.proxyMediaDetailList)),
                                activeNames4: ['1']
                            }
                        })
                    }
                    resolve()
                }).catch(() => {
                    Toast.fail({
                        message: '获取合同详情失败',
                        context: that,
                        selector: '#custom-selector'
                    });
                    reject()
                })
            })
        },
        validateData() {
            // 验证主表单
            if (!this.data.validate.checkForm(this.data.cuForm)) {
                Toast.fail({
                    message: this.data.validate.errorList[0].msg,
                    context: this,
                    selector: '#custom-selector'
                })
                return false
            } else {
                // 验证刊例总价
                for (let i = 0; i < this.data.media_type_count_amount_arr.length; i++) {
                    if (!this.data.media_type_count_amount_arr[i].amount) {
                        Toast.fail({
                            message: '刊例总价中有媒体类型的价格为空，请先设置周期',
                            context: this,
                            selector: '#custom-selector'
                        })
                        return false
                    }
                }
                // 验证媒体形式
                let all_sum = 0
                for (let i = 0; i < this.data.cuForm.billSaleMediaAmountList.length; i++) {
                    const item = this.data.cuForm.billSaleMediaAmountList[i]
                    if (!item.fill_amount) {
                        Toast.fail({
                            message: '媒体形式有总价未填写',
                            context: this,
                            selector: '#custom-selector'
                        })
                        return false
                    } else {
                        all_sum = add(all_sum, item.fill_amount)
                    }
                }
                // 验证代媒体形式
                for (let i = 0; i < this.data.cuForm.billSaleProxyList.length; i++) {
                    var item = this.data.cuForm.billSaleProxyList[i];
                    let sum = 0
                    if (item.proxyMediaDetailList && item.proxyMediaDetailList.length) {
                        for (let j = 0; j < item.proxyMediaDetailList.length; j++) {
                            const tmp = item.proxyMediaDetailList[j]
                            if (!this.data.validateProxyMediaDetail.checkForm(tmp)) {
                                Toast.fail({
                                    message: '代媒体形式' + (i + 1) + '中' + this.data.validateProxyMediaDetail.errorList[0].msg,
                                    context: this,
                                    selector: '#custom-selector'
                                })
                                return false
                            } else {
                                sum = add(sum, tmp.fill_amount)
                            }
                        }
                        if (item.proxy_amount != sum) {
                            Toast.fail({
                                message: '代媒体形式' + (i + 1) + '中代理金额于明细刊例总价不相等 请调整',
                                context: this,
                                selector: '#custom-selector'
                            })
                            return false
                        }
                    } else {
                        if (item.proxy_amount) {
                            Toast.fail({
                                message: '代媒体形式' + (i + 1) + '中代理金额于明细刊例总价不相等 请调整',
                                context: this,
                                selector: '#custom-selector'
                            })
                            return false
                        }
                    }
                    all_sum = add(all_sum, sum)
                }
                // 检查金额
                if (this.data.cuForm.execute_amount != all_sum) {
                    Toast.fail({
                        message: '代媒体形式金额总和加上媒体形式金额总和不等于执行金额',
                        context: this,
                        selector: '#custom-selector'
                    })
                    return false
                } else {
                    return true
                }
            }
        },
        showSettingDialog() {
            if (this.data.cuForm.billSaleMediaCycle === null) {
                this.setData({
                        billSaleMediaCycle: {
                            day: this.data.allDay,
                            cycle_arr: []
                        }
                    }
                )
            } else {
                if (this.data.cuForm.billSaleMediaCycle.cycle_arr) {
                    this.setData({
                        'billSaleMediaCycle': JSON.parse(JSON.stringify(this.data.cuForm.billSaleMediaCycle))
                    })
                } else {
                    const parse = JSON.parse(JSON.stringify(this.data.cuForm.billSaleMediaCycle));
                    parse.cycle_arr = []
                    this.setData({
                        'billSaleMediaCycle': parse
                    })
                }
            }
            this.setData({
                showSettingSaleCycle: true
            })
        },
        onClose() {
            this.setData({
                billSaleMediaCycle: {
                    day: 0,
                    cycle_arr: []
                },
            })
        },
        addMonth() {
            this.data.billSaleMediaCycle.cycle_arr.push('')
            this.setData({
                'billSaleMediaCycle.cycle_arr': this.data.billSaleMediaCycle.cycle_arr
            })
        },
        removeMonth(e) {
            this.data.billSaleMediaCycle.cycle_arr.splice(e.target.dataset.index, 1)
            this.setData({
                'billSaleMediaCycle.cycle_arr': this.data.billSaleMediaCycle.cycle_arr
            })
        },
        onConfirm() {
            if (this.data.billSaleMediaCycle.day >= 0) {
                for (let i = 0; i < this.data.billSaleMediaCycle.cycle_arr.length; i++) {
                    let tmp = this.data.billSaleMediaCycle.cycle_arr[i]
                    if (!tmp || isNaN(tmp) || tmp < 0) {
                        util.showToast('请输入有效的天数')
                        return;
                    }
                }
                const obj = this.data.billSaleMediaCycle
                // 计算价格
                this.data.media_type_count_amount_arr.forEach(item => {
                    if (item.media_type_id !== 1) {
                        if (item.has_price_month) {
                            if (this.data.billSaleMediaCycle.cycle_arr && this.data.billSaleMediaCycle.cycle_arr.length) {
                                let amount = multiply(item.month_price, this.data.billSaleMediaCycle.cycle_arr.length)
                                amount = add(amount, multiply(item.day_price, this.data.billSaleMediaCycle.day))
                                item.amount = multiply(amount, item.spec_count)
                            } else {
                                item.amount = multiply(multiply(item.day_price, this.data.allDay), item.spec_count)
                            }
                        } else {
                            item.amount = multiply(multiply(item.day_price, this.data.allDay), item.spec_count)
                        }
                    }
                })
                this.setData({
                    showSettingSaleCycle: false,
                    'cuForm.billSaleMediaCycle': JSON.parse(JSON.stringify(obj))
                })
                this.setData({
                    media_type_count_amount_arr: this.data.media_type_count_amount_arr
                })
                console.log(this.data.media_type_count_amount_arr)
            } else {
                util.showToast('剩余天数不能小于0')
            }
        },
        save() {
            const req = JSON.parse(JSON.stringify(this.data.cuForm))
            req.mediaPriceList = []
            this.data.media_type_count_amount_arr.forEach(item => {
                req.mediaPriceList.push({
                    media_type_spec_price_id: item.media_type_spec_price_id,
                    price: item.amount
                })
            })
            req.billSaleMediaCycleDTO = req.billSaleMediaCycle
            const that = this
            util.showLoading('保存中')
            network.reqPromise('POST', {
                uri: app.api.billSaleSave,
                params: req,
            }).then(res => {
                util.hideLoading()
                Toast.success({
                    message: '操作成功',
                    context: that,
                    selector: '#custom-selector'
                })
                setTimeout(() => {
                    this.back()
                }, 800)
            }).catch(() => {
                Toast.fail({
                    message: '保存失败',
                    context: that,
                    selector: '#custom-selector'
                })
                util.hideLoading()
            })
        },
        submit() {
            const req = JSON.parse(JSON.stringify(this.data.cuForm))
            req.mediaPriceList = []
            this.data.media_type_count_amount_arr.forEach(item => {
                req.mediaPriceList.push({
                    media_type_spec_price_id: item.media_type_spec_price_id,
                    price: item.amount
                })
            })
            req.billSaleMediaCycleDTO = req.billSaleMediaCycle
            const that = this
            util.showLoading('提交中')
            network.reqPromise('PUT', {
                uri: app.api.billSaleBegin,
                params: req,
            }).then(res => {
                util.hideLoading()
                Toast.success({
                    message: '操作成功',
                    context: that,
                    selector: '#custom-selector'
                })
                setTimeout(() => {
                    this.back()
                }, 800)
            }).catch(() => {
                Toast.fail({
                    message: '保存失败',
                    context: that,
                    selector: '#custom-selector'
                })
                util.hideLoading()
            })
        },
        pass(opinion) {
            const that = this
            util.showLoading('提交中')
            network.reqPromise('PUT', {
                uri: app.api.billSalePass,
                params: {
                    id: that.data.cuForm.id,
                    accrued_amount: that.data.cuForm.accrued_amount,
                    opinion: opinion.detail
                },
            }).then(res => {
                Toast.success({
                    message: '操作成功',
                    context: that,
                    selector: '#custom-selector'
                })
                setTimeout(() => {
                    this.back()
                }, 800)
                util.hideLoading()
            }).catch(() => {
                Toast.fail({
                    message: '保存失败',
                    context: that,
                    selector: '#custom-selector'
                })
                util.hideLoading()
            })
        },
        returnBack(opinion) {
            const that = this
            util.showLoading('提交中')
            network.reqPromise('PUT', {
                uri: app.api.billSaleReturnBack,
                params: {
                    id: that.data.cuForm.id,
                    opinion: opinion.detail
                }
            }).then(res => {
                Toast.success({
                    message: '操作成功',
                    context: that,
                    selector: '#custom-selector'
                })
                setTimeout(() => {
                    this.back()
                }, 800)
                util.hideLoading()
            }).catch(() => {
                Toast.fail({
                    message: '保存失败',
                    context: that,
                    selector: '#custom-selector'
                })
                util.hideLoading()
            })
        },
        del() {
            const that = this
            util.showLoading('提交中')
            network.reqPromise('DELETE', {
                uri: app.api.billSaleDelete,
                params: {
                    id: that.data.cuForm.id,
                },
            }).then(res => {
                Toast.success({
                    message: '操作成功',
                    context: that,
                    selector: '#custom-selector'
                })
                setTimeout(() => {
                    this.back()
                }, 800)
                util.hideLoading()
            }).catch(() => {
                Toast.fail({
                    message: '保存失败',
                    context: that,
                    selector: '#custom-selector'
                })
                util.hideLoading()
            })
        },
        actDel() {
            const that = this
            util.showLoading('提交中')
            network.reqPromise('DELETE', {
                uri: app.api.billSaleActualDelete,
                params: {
                    id: that.data.cuForm.id
                },
            }).then(res => {
                Toast.success({
                    message: '操作成功',
                    context: that,
                    selector: '#custom-selector'
                })
                setTimeout(() => {
                    this.back()
                }, 800)
                util.hideLoading()
            }).catch(() => {
                Toast.fail({
                    message: '保存失败',
                    context: that,
                    selector: '#custom-selector'
                })
                util.hideLoading()
            })
        },
        back() {
            wx.navigateBack({
                    delta: 1
                }
            )
        },
    },
    observers: {
        'cuForm.release_amount': function (value) {
            let sum = 0
            if (!isNaN(parseFloat(this.data.cuForm.replace_amount))) {
                sum = add(sum, this.data.cuForm.replace_amount)
            }
            if (!isNaN(parseFloat(value))) {
                sum = add(sum, value)
            }
            this.setData({
                'cuForm.execute_amount': sum
            })
        },
        'cuForm.replace_amount': function (value) {
            let sum = 0
            if (!isNaN(parseFloat(this.data.cuForm.release_amount))) {
                sum = add(sum, this.data.cuForm.release_amount)
            }
            if (!isNaN(parseFloat(value))) {
                sum = add(sum, value)
            }
            this.setData({
                'cuForm.execute_amount': sum
            })
        },
        'cuForm.actual_execute_time_start': function (val) {
            var startDate = Date.parse(val)
            var endDate = Date.parse(this.data.cuForm.actual_execute_time_end)
            var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
            this.setData({
                allDay: days + 1
            })
        },
        'billSaleMediaCycle.cycle_arr.**': function (val) {
            let sum = 0
            for (let i = 0; i < val.length; i++) {
                if (val[i] && !isNaN(val[i])) {
                    sum += parseInt(val[i])
                }
            }
            this.setData({
                'billSaleMediaCycle.day': this.data.allDay - sum
            })
        },
        'cuForm.actual_execute_time_end': function (val) {
            var startDate = Date.parse(this.data.cuForm.actual_execute_time_start)
            var endDate = Date.parse(val)
            var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
            this.setData({
                allDay: days + 1
            })
        },
        not_fill: function () {
            this.setData({
                accrued_amount: null
            })
        },
        'cuForm.execute_amount': function (val) {
            let sum = 0
            this.data.media_type_count_amount_arr.forEach(item => {
                if (item.amount && !isNaN(item.amount)) {
                    sum += add(item.amount, sum)
                }
            })
            if (!isNaN(val)) {
                let tmp = divide(val, sum).toFixed(4)
                this.setData({
                    'cuForm.discount': multiply(tmp, '100')
                })
            }
        },
        media_type_count_amount_arr: function (val) {
            let sum = 0
            val.forEach(item => {
                if (item.amount && !isNaN(item.amount)) {
                    sum += add(item.amount, sum)
                }
            })
            if (!isNaN(this.data.cuForm.execute_amount)) {
                let tmp = divide(this.data.cuForm.execute_amount, sum).toFixed(4)
                this.setData({
                    'cuForm.discount': multiply(tmp, '100')
                })
            }
        },
        saleId: function (val) {
            if (val > 0) {
                util.showLoading('加载中')
                network.reqPromise('GET', {
                    uri: app.api.billSaleDetail,
                    params: {
                        id: val
                    },
                }).then(res => {
                    this.setData({
                        cuForm: res.data,
                    })
                    this.setData({
                        'media_type_count_amount_arr': res.data.mediaPriceList,
                        'cuForm.billSaleMediaAmountList': res.data.mediaAmountVOList,
                        'cuForm.billSaleProxyList': res.data.billSaleProxies,
                        not_fill: res.data.is_conpany_customer
                    })
                    network.reqPromise("GET", {
                        uri: app.api.contractListByCustomerId,
                        params: {customerId: res.data.customer_id}
                    }).then(res => {
                        res.data.forEach(item => {
                            item.name = item.part_a + '——' + item.contract_num + '（' + item.contract_begin_date + ' ~ ' + item.contract_end_date + '）'
                        })
                        this.setData({
                            contractList: res.data,
                            selectContractLoading: false
                        })
                        const find = res.data.find(item => item.id === this.data.cuForm.contract_id);
                        this.setData({
                            'cuForm.contractAmount': find.discounted_price,
                            'cuForm.contract_id': find.id,
                            'cuForm.contractName': find.name,
                            'cuForm.contract_num': find.contract_num,
                            must_include_id: this.data.cuForm.intention_scheme_id
                        })
                        this.getPlanArr(find.id, this.data.related_type, this.data.must_include_id, this.data.cuForm.type)
                        util.hideLoading()
                    }).catch(err => {
                        util.hideLoading()
                    })
                }).catch(() => {
                    Toast.fail({
                        message: '获取详情失败',
                        context: this,
                        selector: '#custom-selector'
                    })
                    util.hideLoading()
                })
            }
        },
        is_update: function (val) {
            if (val) {
                console.log(this.data.params)
                util.showLoading('加载中')
                network.reqPromise('GET', {
                    uri: app.api.billSaleDetail,
                    params: {
                        id: this.data.params.source_sale_id
                    },
                }).then(res => {
                    this.setData({
                        'cuForm.type': res.data.type,
                        'cuForm.contract_id': res.data.contract_id,
                        'cuForm.customerName': res.data.customerName,
                        'cuForm.customer_id': res.data.customer_id,
                        'cuForm.dept_id': res.data.dept_id,
                        'cuForm.deptName': res.data.deptName
                    })
                    this.setData({
                        // 'media_type_count_amount_arr': res.data.mediaPriceList,
                        // 'cuForm.billSaleMediaAmountList': res.data.mediaAmountVOList,
                        // 'cuForm.billSaleProxyList': res.data.billSaleProxies,
                        not_fill: res.data.is_conpany_customer
                    })
                    network.reqPromise("GET", {
                        uri: app.api.contractListByCustomerId,
                        params: {customerId: res.data.customer_id}
                    }).then(res => {
                        res.data.forEach(item => {
                            item.name = item.part_a + '——' + item.contract_num + '（' + item.contract_begin_date + ' ~ ' + item.contract_end_date + '）'
                        })
                        this.setData({
                            contractList: res.data,
                            selectContractLoading: false
                        })
                        const find = res.data.find(item => item.id === this.data.cuForm.contract_id);
                        // 添加代理媒体
                        this.setData({
                            'cuForm.contractAmount': find.discounted_price,
                            'cuForm.contractName': find.name,
                            'cuForm.contract_num': find.contract_num,
                            must_include_id: this.data.params.plan_id,
                            tmpContract: find
                        })
                        this.getContractDetail(find.id).then(() => {
                            // 加载锁位方案
                            this.getPlanArr(find.id, this.data.related_type, this.data.must_include_id, this.data.cuForm.type).then(res => {
                                for (let i = 0; i < res.length; i++) {
                                    if (this.data.params.plan_id == res[i].id) {
                                        this.setData({
                                            'cuForm.intention_scheme_id': this.data.params.plan_id,
                                            'cuForm.planName': res[i].plan_name,
                                            'cuForm.actual_execute_time_start': res[i].daterange_start_at,
                                            'cuForm.actual_execute_time_end': res[i].daterange_end_at,
                                            'cuForm.choose_id': res[i].choose_id,
                                            'cuForm.daterange_id': res[i].daterange_id
                                        })
                                        const that = this
                                        network.reqPromise("GET", {
                                            uri: app.api.media_type_count_amount,
                                            params: {
                                                customerId: that.data.cuForm.customer_id,
                                                dateRangeId: that.data.cuForm.daterange_id
                                            }
                                        }).then(res => {
                                            for (let i = 0; i < res.data.length; i++) {
                                                if (res.data[i].media_type_id !== 1) {
                                                    res.data[i].amount = null
                                                }
                                            }
                                            that.setData({
                                                media_type_count_amount_arr: res.data.filter(item => item.spec_count != 0)
                                            })
                                            that.setData({
                                                'cuForm.billSaleMediaAmountList': res.data.filter(item => item.spec_count != 0).map(item => {
                                                    return {
                                                        media_type_spec_id: item.media_type_spec_id,
                                                        media_type_spec_price_id: item.media_type_spec_price_id,
                                                        name: item.name,
                                                        media_count: item.spec_count,
                                                        fill_amount: null,
                                                        has_price_day: item.has_price_day,
                                                        has_price_week: item.has_price_week,
                                                        has_price_month: item.has_price_month,
                                                        price: null
                                                    }
                                                })
                                            })
                                            util.hideLoading()
                                        }).catch(() => {
                                            Toast.fail({
                                                message: '获取刊例总价失败',
                                                context: that,
                                                selector: '#custom-selector'
                                            });
                                            util.hideLoading()
                                        })
                                    }
                                }
                                util.hideLoading()
                            }).catch(() => {
                                util.hideLoading()
                            })
                        })
                    }).catch(err => {
                        util.hideLoading()
                    })
                }).catch(() => {
                    Toast.fail({
                        message: '获取详情失败',
                        context: this,
                        selector: '#custom-selector'
                    })
                    util.hideLoading()
                })
            }
        }
    },
})
